package bb.lanxing.lib.devices.ble.device;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.base.SimpleBluetoothGattCallbackCompat;
import bb.lanxing.lib.devices.ble.BLEAttributes;
import bb.lanxing.lib.devices.core.ble.AbsBleDevice;
import bb.lanxing.lib.devices.core.provider.DataNotifier;
import java.util.UUID;
import android.util.Log;


public class StandardPowerrateDevice extends AbsBleDevice {
    final static private boolean DebugPower = false;
    public StandardPowerrateDevice(Context context, SmartDevice smartDevice) {
        super(smartDevice);
        init(context, smartDevice.getAddress(), new PowerrateBluetoothGattCallback(this));
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onServicesDiscovered() {
        super.onServicesDiscovered();
        BluetoothGattCharacteristic characteristic = mBluetoothGatt.getService(UUID.fromString(BLEAttributes.BLE_CYCLING_POWER_SERVICE)).getCharacteristic(UUID.fromString(BLEAttributes.BLE_CYCLING_POWER_CHAR_MEASURE));
        mBluetoothGatt.readCharacteristic(characteristic);
        setCharacteristicNotification(characteristic, true);
    }

    private static class PowerrateBluetoothGattCallback extends SimpleBluetoothGattCallbackCompat<StandardPowerrateDevice> {
        PowerrateBluetoothGattCallback(StandardPowerrateDevice standardPowerrateDevice) {
            super(standardPowerrateDevice);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
            int intValue;
            super.onCharacteristicChanged(bluetoothGatt, bluetoothGattCharacteristic);
            UUID uuid = bluetoothGattCharacteristic.getUuid();
            int type = ((StandardPowerrateDevice) this.mClientRef).getType();
            if (UUID.fromString(BLEAttributes.BLE_CYCLING_POWER_CHAR_MEASURE).equals(uuid)) {
                if(DebugPower) {
                    intValue = bluetoothGattCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);;
                }
                else{
                    intValue = bluetoothGattCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT16, 2);
                }
                DataNotifier.notifyPowerrateData(type, ((StandardPowerrateDevice) this.mClientRef).getAddress(), intValue);
            }
        }
    }
}
